package lx.exalarm.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;

import java.util.List;

import lx.exalarm.R;
import lx.exalarm.alarm.ActionBean;
import lx.exalarm.alarm.AlarmBean;
import lx.exalarm.alarm.AlarmUtils;
import lx.exalarm.base.BaseActivity;
import lx.exalarm.database.DBManager;
import lx.exalarm.utils.log.Log;
import lx.exalarm.view.WeekdayView;
import lx.exalarm.view.switchbutton.SwitchButton;

/**
 * Created by liuxu on 15-2-27.
 */
public class ActivityAlarm extends BaseActivity
        implements BaseActivity.ActionBarImpl, View.OnClickListener,
        AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    private static final String EXTRA_ALARM_ID = "extra_alarm_bean_id";
    private static final int AC_REQUEST_CODE_ACTION = 101;

    private AlarmBean mAlarmBean;
    private ActionAdapter mAdapter;
    private int mActionSelected;

    private ListView mListView;
    private NumberPicker mPickerHour;
    private NumberPicker mPickerMinute;
    private WeekdayView mWeekdayView;

    private NumberPicker.Formatter mHourFormatter = new NumberPicker.Formatter() {
        @Override
        public String format(int value) {
            String tmpStr = String.valueOf(value);
            if (value < 10) {
                tmpStr = "0" + tmpStr;
            }
            return tmpStr;
        }
    };

    private NumberPicker.Formatter mMinuteFormatter = new NumberPicker.Formatter() {
        @Override
        public String format(int value) {
            int time = value * 5;
            String tmpStr = String.valueOf(time);
            if (time < 10) {
                tmpStr = "0" + tmpStr;
            }
            return tmpStr;
        }
    };

    public static void start(Context cxt, AlarmBean alarm) {
        Intent intent = new Intent(cxt, ActivityAlarm.class);
        if (alarm != null) {
            intent.putExtra(EXTRA_ALARM_ID, alarm.getId());
        }
        cxt.startActivity(intent);
    }

    public static void start(Context cxt) {
        Intent intent = new Intent(cxt, ActivityAlarm.class);
        cxt.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);

        int alarmId = getIntent().getIntExtra(EXTRA_ALARM_ID, -1);
        if (alarmId != -1) {
            mAlarmBean = DBManager.getInstance().getAlarm(alarmId);
        } else {
            // new alarm
            mAlarmBean = AlarmBean.createDefaultAlarm();
        }

        Log.d("ActivityAlarm, onCreate, alarm: " + mAlarmBean);
        initView();
        mAdapter = new ActionAdapter(this, mAlarmBean);
        mListView.setAdapter(mAdapter);
        mWeekdayView.setAlarm(mAlarmBean, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0) {
            return;
        }

        switch (requestCode) {
            case AC_REQUEST_CODE_ACTION: {
                ActionBean action = (ActionBean)
                        data.getSerializableExtra(ActivityAction.EXTRA_ACTION);
                ActionBean actionHere = mAlarmBean.getActions().get(mActionSelected);
                
                Log.d("ActivityAlarm, onActivityResult, action=" + action);
                if (action != null && action.getId() == actionHere.getId()) {
                    actionHere.setInterval(action.getInterval());
                    actionHere.setDurance(action.getDurance());
                    actionHere.setType(action.getType());
                    actionHere.setData(action.getData());
                    mAdapter.dataChanged(mAlarmBean);
                }
                break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initView() {
        getView(R.id.aa_btn_cancel).setOnClickListener(this);
        getView(R.id.aa_btn_confirm).setOnClickListener(this);

        mPickerHour = getView(R.id.aa_np_hour);
        mPickerHour.setFormatter(mHourFormatter);
        mPickerHour.setMinValue(0);
        mPickerHour.setMaxValue(23);
        mPickerHour.setValue(mAlarmBean.getHour());

        mPickerMinute = getView(R.id.aa_np_minute);
        mPickerMinute.setFormatter(mMinuteFormatter);
        mPickerMinute.setMinValue(0);
        mPickerMinute.setMaxValue(11);
        mPickerMinute.setValue(mAlarmBean.getMinute() / 5);

        mListView = getView(R.id.aa_action_listview);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);

        mWeekdayView = getView(R.id.aa_weekday);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.aa_btn_confirm: {
                mAlarmBean.setHour(mPickerHour.getValue());
                mAlarmBean.setMinute(mPickerMinute.getValue() * 5);
                if (mAlarmBean.getId() == -1) {
                    // new alarm
                    DBManager.getInstance().addAlarm(mAlarmBean);
                } else {
                    DBManager.getInstance().updateAlarm(mAlarmBean, true);
                }
                AlarmUtils.updateAlarm(mAlarmBean);
                finish();
                break;
            }
            case R.id.aa_btn_cancel: {
                finish();
                break;
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ActionAdapter adapter = (ActionAdapter) parent.getAdapter();
        ActionBean action = adapter.getItem(position);
        mActionSelected = position;
        ActivityAction.startForResult(this, AC_REQUEST_CODE_ACTION, action);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        ActionAdapter adapter = (ActionAdapter) parent.getAdapter();
        final ActionBean action = adapter.getItem(position);
        AlertDialog dlg = new AlertDialog.Builder(this)
                .setMessage(R.string.dlg_delete_alarm_msg)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO
                        //DBManager.getInstance().deleteAction(action);
                        //mAlarmBean.getActions().remove(action);
                        //mAdapter.dataChanged(mAlarmBean);
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .create();
        dlg.show();
        return true;
    }


    private static class ActionAdapter extends BaseAdapter {

        private List<ActionBean> mList;
        private Context mContext;

        ActionAdapter(Context cxt, AlarmBean alarm) {
            mContext = cxt;
            mList = alarm.getActions();
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public ActionBean getItem(int position) {
            return mList == null ? null : mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ActionBean action = getItem(position);
            ViewHolder h;

            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(mContext);
                View view = inflater.inflate(R.layout.item_action, null);
                h = new ViewHolder();
                h.mSequence = (TextView) view.findViewById(R.id.item_action_sequence);
                h.mMediaType = (TextView) view.findViewById(R.id.item_action_type);
                h.mTimeDetail = (TextView) view.findViewById(R.id.item_action_time_detail);
                h.mSwitch = (SwitchButton) view.findViewById(R.id.item_action_switch);
                view.setTag(h);
                convertView = view;
            } else {
                h = (ViewHolder) convertView.getTag();
            }

            h.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked && !action.isEnabled()) {
                        action.setEnabled(true);
                    } else if (!isChecked && action.isEnabled()) {
                        action.setEnabled(false);
                    }
                }
            });
            h.mSequence.setText(String.valueOf(position + 1));
            h.mMediaType.setText(action.getTypeString());
            h.mTimeDetail.setText(mContext.getString(R.string.activity_action_time_detail,
                    action.getInterval()));
            h.mSwitch.setChecked(action.isEnabled());

            return convertView;
        }

        public void dataChanged(AlarmBean alarm) {
            mList = alarm.getActions();
            notifyDataSetChanged();
        }

        static class ViewHolder {
            TextView mSequence;
            TextView mMediaType;
            TextView mTimeDetail;
            SwitchButton mSwitch;
        }
    }
}
